package com.example.demotest.service;

import com.example.demotest.pojo.Chat;
import com.example.demotest.pojo.Message;
import com.example.demotest.pojo.Product;
import com.example.demotest.pojo.User;
import com.example.demotest.pojo.dto.*;
import com.example.demotest.repository.ChatRepository;
import com.example.demotest.repository.MessageRepository;
import com.example.demotest.repository.ProductRepository;
import com.example.demotest.repository.UserRepository;
import com.example.demotest.util.JWT;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ChatService implements IChatService {

    private final ChatRepository chatRepository;
    private final MessageRepository messageRepository;
    private final ProductRepository productRepository;
    private final UserRepository userRepository;
    private final ModelMapper modelMapper;
    private final JWT jwtUtil;

    @Autowired
    public ChatService(ChatRepository chatRepository,
                       MessageRepository messageRepository,
                       ProductRepository productRepository,
                       UserRepository userRepository,
                       ModelMapper modelMapper,
                       JWT jwtUtil) {
        this.chatRepository = chatRepository;
        this.messageRepository = messageRepository;
        this.productRepository = productRepository;
        this.userRepository = userRepository;
        this.modelMapper = modelMapper;
        this.jwtUtil = jwtUtil;
    }

    @Override
    @Transactional
    public ChatDto startChat(ChatCreateDto chatCreateDto, HttpServletRequest request) {
        // 从token中获取买家ID
        String token = jwtUtil.extractToken(request);
        if (token == null || !jwtUtil.validateToken(token)) {
            throw new IllegalArgumentException("请先登录");
        }
        Integer buyerId = jwtUtil.getUserIdFromToken(token);

        // 从商品ID获取卖家ID
        Product product = productRepository.findById(chatCreateDto.getProductId().intValue())
                .orElseThrow(() -> new IllegalArgumentException("商品不存在"));
        Integer sellerId = product.getUserId();

        // 检查是否已存在活跃的聊天会话
        List<Chat> existingChats = chatRepository.findByBuyerIdAndSellerId(
                buyerId.longValue(),
                sellerId.longValue()
        );

        Optional<Chat> activeChat = existingChats.stream()
                .filter(Chat::getIsActive)
                .findFirst();

        if (activeChat.isPresent()) {
            throw new IllegalArgumentException("已存在活跃的聊天会话");
        }

        // 创建新的聊天会话
        Chat chat = new Chat();
        chat.setBuyerId(buyerId.longValue());
        chat.setSellerId(sellerId.longValue());
        chat.setProductId(chatCreateDto.getProductId());
        chat.setCreatedAt(LocalDateTime.now());
        chat.setIsActive(true);

        Chat savedChat = chatRepository.save(chat);

        // 添加初始消息
        Message initialMessage = new Message();
        initialMessage.setChatId(savedChat.getId());
        initialMessage.setSenderId(buyerId.longValue());
        initialMessage.setContent(chatCreateDto.getInitialMessage());
        initialMessage.setTimestamp(LocalDateTime.now());
        messageRepository.save(initialMessage);

        return modelMapper.map(savedChat, ChatDto.class);
    }

    @Override
    @Transactional
    public MessageDto sendMessage(Long chatId, MessageSendDto messageSendDto, HttpServletRequest request) {
        // 从token中获取发送者ID
        String token = jwtUtil.extractToken(request);
        if (token == null || !jwtUtil.validateToken(token)) {
            throw new IllegalArgumentException("请先登录");
        }
        Integer senderId = jwtUtil.getUserIdFromToken(token);

        Chat chat = chatRepository.findById(chatId)
                .filter(Chat::getIsActive)
                .orElseThrow(() -> new IllegalArgumentException("聊天会话不存在或已结束"));

        if (!senderId.equals(chat.getBuyerId().intValue()) &&
                !senderId.equals(chat.getSellerId().intValue())) {
            throw new IllegalArgumentException("不是会话参与者，无法发送消息");
        }

        Message message = new Message();
        message.setChatId(chatId);
        message.setSenderId(senderId.longValue());
        message.setContent(messageSendDto.getContent());
        message.setTimestamp(LocalDateTime.now());

        Message savedMessage = messageRepository.save(message);
        return modelMapper.map(savedMessage, MessageDto.class);
    }

    @Override
    public List<MessageDto> getChatHistory(Long chatId) {
        Chat chat = chatRepository.findById(chatId)
                .orElseThrow(() -> new IllegalArgumentException("聊天会话不存在"));

        List<Message> messages = messageRepository.findByChatIdOrderByTimestampAsc(chatId);
        return messages.stream()
                .map(message -> {
                    MessageDto dto = modelMapper.map(message, MessageDto.class);
                    // 获取发送者信息
                    User sender = userRepository.findById(message.getSenderId().intValue())
                            .orElseThrow(() -> new IllegalArgumentException("发送者不存在"));
                    dto.setSenderNickname(sender.getNickname());
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void endChat(Long chatId) {
        Chat chat = chatRepository.findById(chatId)
                .orElseThrow(() -> new IllegalArgumentException("聊天会话不存在"));

        if (!chat.getIsActive()) {
            throw new IllegalArgumentException("聊天会话已结束");
        }

        chat.setIsActive(false);
        chatRepository.save(chat);
    }

    @Override
    public List<ChatDto> getUserChats(HttpServletRequest request) {
        // 从token中获取用户ID
        String token = jwtUtil.extractToken(request);
        if (token == null || !jwtUtil.validateToken(token)) {
            throw new IllegalArgumentException("请先登录");
        }
        Integer userId = jwtUtil.getUserIdFromToken(token);

        List<Chat> chats = chatRepository.findByBuyerIdOrSellerIdOrderByCreatedAtDesc(
                userId.longValue(),
                userId.longValue());

        return chats.stream()
                .map(chat -> {
                    ChatDto dto = modelMapper.map(chat, ChatDto.class);
                    // 获取最后一条消息
                    List<Message> messages = messageRepository.findByChatIdOrderByTimestampDesc(chat.getId());
                    if (!messages.isEmpty()) {
                        Message lastMessage = messages.get(0);
                        dto.setLastMessage(lastMessage.getContent());
                        dto.setLastMessageSenderId(lastMessage.getSenderId());
                        dto.setLastMessageTime(lastMessage.getTimestamp());
                        // 获取发送者昵称
                        User sender = userRepository.findById(lastMessage.getSenderId().intValue())
                                .orElseThrow(() -> new IllegalArgumentException("发送者不存在"));
                        dto.setLastMessageSenderNickname(sender.getNickname());
                    }
                    return dto;
                })
                .collect(Collectors.toList());
    }
}